package com.lmabbe.core.service.impls;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmabbe.common.global.context.LmabbeSessionUser;
import com.lmabbe.core.common.converter.SysResourceConverter;
import com.lmabbe.core.common.entitys.SysResource;
import com.lmabbe.core.common.interfaces.SysResourceService;
import com.lmabbe.core.common.interfaces.SysRoleResourceService;
import com.lmabbe.core.common.query.SysResourceQuery;
import com.lmabbe.core.common.vo.SysResourceTreeVO;
import com.lmabbe.core.service.dao.SysResourceMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lmabbe
 */
@Slf4j
@DubboService(provider = "simple-dubbo")
@RequiredArgsConstructor
public class SysResourceServiceImpl extends ServiceImpl<SysResourceMapper, SysResource> implements SysResourceService {

    private final LmabbeSessionUser lmabbeSessionUser;
    private final SysRoleResourceService sysRoleResourceService;
    private final SysResourceConverter sysResourceConverter;

    @Override
    public List<SysResourceTreeVO> getTreeList() {
        List<SysResource> resources = sysRoleResourceService.findResourceByUserId(lmabbeSessionUser.getUserId());
        List<SysResourceTreeVO> roots = resources.parallelStream()
                .filter(resource -> resource.getParentId() == null || resource.getParentId() == 0)
                .sorted(Comparator.comparing(SysResource::getSortValue))
                .map(resource -> sysResourceConverter.entity2TreeVo(resource))
                .collect(Collectors.toList());
        list2Tree(resources, roots);
        return roots;
    }

    /**
     * 转成树菜单
     *
     * @param all   :
     * @param roots :
     * @date 2021/12/4 18:58
     * @author liming
     */
    private void list2Tree(List<SysResource> all, List<SysResourceTreeVO> roots) {
        for (SysResourceTreeVO root : roots) {
            List<SysResource> sons = all.parallelStream()
                    .filter(s -> s.getParentId().equals(root.getResourceId()))
                    .sorted(Comparator.comparing(SysResource::getSortValue))
                    .collect(Collectors.toList());
            root.setChildren(sons.parallelStream()
                    .map(s -> sysResourceConverter.entity2TreeVo(s))
                    .collect(Collectors.toList()));
            list2Tree(all, root.getChildren());
        }
    }

    @Override
    public IPage selectPage(SysResourceQuery query) {
        return baseMapper.selectPage(query.createPage(), query.createQuery());
    }
}
